package com.ciwong.epaper.modules.reciteWords.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.common.db.DBCallBack;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.reciteWords.bean.PlanAndWorListBean;
import com.ciwong.epaper.modules.reciteWords.bean.TodayAndReviewWordBean;
import com.ciwong.epaper.modules.reciteWords.bean.WordPlanViewType;
import com.ciwong.epaper.modules.reciteWords.dao.WordDao;
import com.ciwong.epaper.modules.reciteWords.dbreciteword.BaseDBManager;
import com.ciwong.epaper.modules.reciteWords.dbreciteword.DBWordBookStateManagerAsyn;
import com.ciwong.epaper.modules.reciteWords.util.WordJumpManager;
import com.ciwong.epaper.modules.reciteWords.util.WordUtil;
import com.ciwong.epaper.modules.reciteWords.util.download.DeserializeCallBack;
import com.ciwong.epaper.modules.reciteWords.util.download.DownloadCallBack;
import com.ciwong.epaper.modules.reciteWords.util.download.WordBookDownloadManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DateUtils;
import com.ciwong.epaper.util.DoubleClickCheckUtils;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.epaper.widget.WordPlanNumberView;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.DownloadProgressBar;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by keepon on 2018/9/3.
 */
public class WordPlanActivity extends BaseActivity implements View.OnClickListener {
    private CardView mCardView1, mCardView2;
    private RelativeLayout mRlTodayLearning, mRlTodayFinsh, mRlNormal;
    private TextView mTvBookName, mTvChangePlan, mTvLearnedOfAll, mTvWordAll, mTvTodayLearn, mTvTodayRevise,
            mTvMore5, mTvLearnOtherWord, mTvMaterialBook, mTvWorkList, mTvLearnAgain;
    private WordPlanNumberView mOneDayNumber, mRestDayCount;

    private LinearLayout mLlNoNet, mLlGetDataFailed;
    private Button mBtnRetry, mBtnPk1, mBtnPk2, mBtnFailedRetry, mBtnDakaView;
    private ProgressBar mProgressBar;
    private Button mBtnReciteWord;
    private ImageView mIvline;
    private PlanAndWorListBean mPlanAndWorListBean;
    //最后完成计划的时间是否是今天
    private boolean mIsLastCompleteIsToday;
    private int mLocalWordFirstInterpretationId;
    private int flag = -1;
    private int JUMP_TO_RECITE_WORD_LIST = 1;
    private int JUMP_TO_RECITE_WORD_START_OR_MORE = 2;
    private CopyOnWriteArrayList<WordDetail> mTodayWords = new CopyOnWriteArrayList<WordDetail>();
    //-1表示没学过
    private int REVIEW_WORDS_TO_REVIEW = -1;//需复习单词个数

    private int COMPETE_WORD_INDEX = 0;//今日3遍都完成单词索引
    private int TODAY_NEW_WORD_INDEX = 0;//今日学习单词已学1遍索引

    private int CURRENT_PLAN_WORD_COUNT = -1;//当前计划每次计划学习的单词个数
    //上传的单词索引
    ArrayList<Integer> mWordArray = new ArrayList<>();
    private long mCompleteTime;
    private DownLoadInfo downLoadInfo;

    @Override
    protected int setView() {
        return R.layout.activity_word_plan;
    }

    @Override
    protected void findViews() {
        mCardView1 = findViewById(R.id.card_view_1);
        mCardView2 = findViewById(R.id.card_view_2);
        mTvBookName = findViewById(R.id.tv_book_name);
        mTvChangePlan = findViewById(R.id.tv_change_plan);
        mRestDayCount = findViewById(R.id.word_plan_days);
        mOneDayNumber = findViewById(R.id.word_plan_days_count);
        mTvLearnedOfAll = findViewById(R.id.tv_learned_of_all);
        mTvWordAll = findViewById(R.id.tv_word_all);
        mProgressBar = findViewById(R.id.progressBar);
        mTvTodayLearn = findViewById(R.id.tv_today_learn);
        mTvTodayRevise = findViewById(R.id.tv_today_revise);
        mBtnReciteWord = findViewById(R.id.btn_recite_word);
        mIvline = findViewById(R.id.iv_condition2_line);
        mTvMore5 = findViewById(R.id.tv_more5);
        mTvLearnAgain = findViewById(R.id.tv_learn_again);
        mTvWorkList = findViewById(R.id.tv_word_list);
        mTvMaterialBook = findViewById(R.id.tv_material_book_name);
        mTvLearnOtherWord = findViewById(R.id.tv_learn_other_word);
        mRlTodayFinsh = findViewById(R.id.rl_today_finsh);
        mRlTodayLearning = findViewById(R.id.rl_learning);
        mRlNormal = findViewById(R.id.rl_normal);
        mLlNoNet = findViewById(R.id.ll_no_net);
        mBtnRetry = findViewById(R.id.btn_retry);
        mBtnPk1 = findViewById(R.id.btn_word_pk_1);
        mBtnPk2 = findViewById(R.id.btn_word_pk_2);
        mBtnDakaView = findViewById(R.id.btn_word_daka);
        mLlGetDataFailed = findViewById(R.id.ll_get_data_failed);
        mBtnFailedRetry = findViewById(R.id.btn_failed_retry);
    }

    @Override
    protected void initEvent() {
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }

        mBtnDakaView.setOnClickListener(this);
        mBtnReciteWord.setOnClickListener(this);
        mTvChangePlan.setOnClickListener(this);
        mTvLearnOtherWord.setOnClickListener(this);
        mBtnRetry.setOnClickListener(this);
        mBtnFailedRetry.setOnClickListener(this);
        mBtnPk1.setOnClickListener(this);
        mBtnPk2.setOnClickListener(this);
        mTvMore5.setOnClickListener(this);
        mTvWorkList.setOnClickListener(this);
        mTvLearnAgain.setOnClickListener(this);

        setDownloadProgressOnDismissListener(new DownloadProgressBar.OnDownLoadDialogDismissListener() {
            @Override
            public void ondDismiss(DownloadProgressBar downloadProgressBar) {
                if (downLoadInfo != null) {
                    int status = downLoadInfo.getStatus();
                    if (status == DownloadStatus.STATUS_LOADING || status == DownloadStatus.STATUS_DOWNLOADING) {
                        WordBookDownloadManager.pauseTask(downLoadInfo);
                    }
                }


            }
        });

    }

    @Override
    protected void init() {
        setTitleText("背单词");
        Intent intent = getIntent();
        if (intent != null) {
            mPlanAndWorListBean = (PlanAndWorListBean) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_WORD_PLAN_BEAN);
        }
    }

    @Override
    protected void loadData() {

        mWordArray.clear();
        mLocalWordFirstInterpretationId = 0;
        resetIndexDefaultValue();

        SerializableManager.getInstance().deSerialize(ListenSpeakUtil.getReviewNewWordKey(), new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                getDataFromNet();
            }

            @Override
            public void failed(Object data) {
                getDataFromNet();
            }

            @Override
            public void success(Object data) {
                if (data instanceof CopyOnWriteArrayList) {
                    mTodayWords = (CopyOnWriteArrayList<WordDetail>) data;


                    if (mTodayWords != null && mTodayWords.size() > 0) {
                        //本地有记录，索引值才有用，否则使用默认的
                        getRecordIndex(mTodayWords.size());
                        mLocalWordFirstInterpretationId = Integer.parseInt(mTodayWords.get(0).getdId());
                        //本次计划的单词是否全部完成，全部完成则加入mWordArray，否则mWordArray传空
                        if (COMPETE_WORD_INDEX != 0 && mTodayWords.size() == COMPETE_WORD_INDEX) {
                            for (WordDetail todayWord : mTodayWords) {
                                mWordArray.add(Integer.parseInt(todayWord.getdId()));
                            }
                        }

                    }
                }
                getDataFromNet();
            }
        });


    }

    /**
     * public static  int  REVIEW_YESTERDAY_WORD=1;//复习昨日单词
     * public static  int  STUDY_TODAY_WORD=2;//学习今日单词
     * public static  int  REVIEW_TODAY_WORD=3;//复习今日单词第一遍
     * public static  int REVIEW_TODAY_WORD_SECOND=4;//复习今日单词第二遍
     * public static  int REVIEW_TODAY_WORD_THIRD=5;//复习今日单词第3遍
     */

    private void getRecordIndex(int todayListSize) {
        int study_type = CWSys.getSharedInt(ListenSpeakUtil.getStudyTypeKey(), 0);
        int currentStudyIndex = CWSys.getSharedInt(ListenSpeakUtil.getCurrentNewWordKey(), 0);
        Log.e(TAG, "dealData: study_type =" + study_type + "  currentStudyIndex==" + currentStudyIndex);
        REVIEW_WORDS_TO_REVIEW = CWSys.getSharedInt(ListenSpeakUtil.getReviewWordToReviewKey(), -1);
        //本次计划未进入过开始背单词页面
        if (study_type == 0) {
            COMPETE_WORD_INDEX = 0;
            TODAY_NEW_WORD_INDEX = 0;
        } else if (study_type == WordStudyActivity.STUDY_TODAY_WORD) {
            COMPETE_WORD_INDEX = 0;
            TODAY_NEW_WORD_INDEX = currentStudyIndex;
        } else if (study_type == WordStudyActivity.REVIEW_TODAY_WORD || study_type == WordStudyActivity.REVIEW_TODAY_WORD_SECOND ||
                study_type == WordStudyActivity.REVIEW_TODAY_WORD_THIRD) {
            //表示第一遍已经学完
            TODAY_NEW_WORD_INDEX = todayListSize;
            //study_type==WordStudyActivity.REVIEW_TODAY_WORD_THIRD，今日3遍都完成单词索引
            if (study_type == WordStudyActivity.REVIEW_TODAY_WORD_THIRD) {
                COMPETE_WORD_INDEX = currentStudyIndex;
            } else {
                COMPETE_WORD_INDEX = 0;
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().unregister(this);
            hideDownloadProgress();
        }
    }

    private void getDataFromNet() {
        Log.e(TAG, "dealData: " + "  REVIEW_WORDS_TO_REVIEW==" + REVIEW_WORDS_TO_REVIEW + "  COMPETE_WORD_INDEX==" + COMPETE_WORD_INDEX + "  TODAY_NEW_WORD_INDEX==" + TODAY_NEW_WORD_INDEX + "  mTodayList.size==" + (mTodayWords == null ? null : mTodayWords.size()));
        int userId = (int) EApplication.getInstance().getUserInfoBase().getUserId();
        showCricleProgress();
        WordDao.getInstance().submitWord(userId, mWordArray, new BaseExtCallBack(WordPlanActivity.this) {
            @Override
            public void failed(int errorCode, Object data) {
                if (errorCode == -1) {
                    hideCricleProgress();
                    //计划被清掉跳到选择教材页面
                    WordJumpManager.jumpToSelectVacabularyActivity(R.string.go_back, WordPlanActivity.this, 0, IntentValue.JumpSelectVocabularyType.NORMAL);
                    finish();
                } else {
                    hideCricleProgress();
                    super.failed(errorCode, data);
                    showViewByType(WordPlanViewType.VIEW_TYPE_FAILED_ERROR, null);
                }

            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                if (!NetworkUtils.isOnline()) {
                    showViewByType(WordPlanViewType.VIEW_TYPE_NO_NET_ERROR, null);
                } else {
                    showViewByType(WordPlanViewType.VIEW_TYPE_FAILED_ERROR, null);
                }

            }

            @Override
            public void success(Object data) {
                if (data != null && data instanceof PlanAndWorListBean) {
                    PlanAndWorListBean planAndWorListBean = (PlanAndWorListBean) data;
                    //BOOKID全局赋值
                    BaseDBManager.BOOK_ID = planAndWorListBean.getBookId() + "";

                    mCompleteTime = CWSys.getSharedLong(ListenSpeakUtil.getCompleteTimeKey(), 0);
                    //上次做完是否是今天
                    mIsLastCompleteIsToday = DateUtils.isToday(new Date(mCompleteTime));
                    CURRENT_PLAN_WORD_COUNT = CWSys.getSharedInt(ListenSpeakUtil.getCurrentPlanWordCountKey(), CURRENT_PLAN_WORD_COUNT);

                    //本次计划完成提交成功后删除记录
                    if (mWordArray.size() > 0) {
                        clearStudyRecordAndResetDefaultValue();
                    }
                    //如果返回的每次计划单词个数与本地的不一样，删除本地记录
                    if (CURRENT_PLAN_WORD_COUNT != -1 && CURRENT_PLAN_WORD_COUNT != planAndWorListBean.getDayCount()) {
                        clearStudyRecordAndResetDefaultValue();
                    }

                    dealData(planAndWorListBean);

                } else {
                    hideCricleProgress();
                    //计划被清掉跳到选择教材页面
                    finish();
                    WordJumpManager.jumpToSelectVacabularyActivity(R.string.go_back, WordPlanActivity.this, 0, IntentValue.JumpSelectVocabularyType.NORMAL);

                }

            }
        });
    }

    private void clearStudyRecordAndResetDefaultValue() {
        Log.e(TAG, " dealData clearStudyRecordAndResetDefaultValue:  ");
        WordUtil.clearStudyRecord();
        mWordArray.clear();
        resetIndexDefaultValue();
    }

    private void resetIndexDefaultValue() {
        REVIEW_WORDS_TO_REVIEW = -1;
        COMPETE_WORD_INDEX = 0;
        TODAY_NEW_WORD_INDEX = 0;
    }

    private void dealData(PlanAndWorListBean planAndWorListBean) {
        mPlanAndWorListBean = planAndWorListBean;

        //本地数据是否存在于服务器返回的列表中
        boolean isServiceList = false;
        WordPlanViewType wordPlanViewType;
        //保存本次计划一次学几个单词
        CWSys.setSharedInt(ListenSpeakUtil.getCurrentPlanWordCountKey(), planAndWorListBean.getDayCount());
        //这本书计划是否已经完成
        if (planAndWorListBean.getCompletecount() == planAndWorListBean.getWordsum()) {
            wordPlanViewType = WordPlanViewType.VIEW_TTPE_TOTAL_FINISH;
        } else {
            List<TodayAndReviewWordBean> today = planAndWorListBean.getToday();
            //第一个索引的InterpretationId是否一致
            if (today != null && today.size() > 0) {
                TodayAndReviewWordBean todayAndReviewWordBean = today.get(0);
                if (mLocalWordFirstInterpretationId == todayAndReviewWordBean.getInterpretationId()) {
                    isServiceList = true;
                }
            }
            if (isServiceList) {
                //本地列表与服务器列表一致，肯定是学习中状态
                wordPlanViewType = WordPlanViewType.VIEW_TTPE_LEARNNING;
            } else {
                if (mIsLastCompleteIsToday) {
                    wordPlanViewType = WordPlanViewType.VIEW_TTPE_TODAY_FINISH;
                } else {
                    //删除本次记录
                    clearStudyRecordAndResetDefaultValue();
                    wordPlanViewType = WordPlanViewType.VIEW_TTPE_LEARNNING;
                }
            }
            Log.e(TAG, "dealData: isServiceList =" + isServiceList + "  mIsLastCompleteIsToday==" + mIsLastCompleteIsToday + "  CURRENT_PLAN_WORD_COUNT==" + CURRENT_PLAN_WORD_COUNT);
        }


        showViewByType(wordPlanViewType, planAndWorListBean);
    }

    private void showViewByType(WordPlanViewType wordPlanViewType, PlanAndWorListBean planAndWorListBean) {
//		wordPlanViewType = WordPlanViewType.VIEW_TTPE_TOTAL_FINISH;
        if (wordPlanViewType == WordPlanViewType.VIEW_TYPE_NO_NET_ERROR) {
            mRlNormal.setVisibility(View.GONE);
            mLlNoNet.setVisibility(View.VISIBLE);
            mLlGetDataFailed.setVisibility(View.GONE);
        } else if (wordPlanViewType == WordPlanViewType.VIEW_TYPE_FAILED_ERROR) {
            mRlNormal.setVisibility(View.GONE);
            mLlNoNet.setVisibility(View.GONE);
            mLlGetDataFailed.setVisibility(View.VISIBLE);
        } else {
            mRlNormal.setVisibility(View.VISIBLE);
            mLlNoNet.setVisibility(View.GONE);
            mLlGetDataFailed.setVisibility(View.GONE);
            if (wordPlanViewType == WordPlanViewType.VIEW_TTPE_TOTAL_FINISH) {
                mTvMaterialBook.setText(planAndWorListBean.getPlanName());
                mCardView2.setVisibility(View.VISIBLE);
                mCardView1.setVisibility(View.GONE);
                mRlTodayLearning.setVisibility(View.GONE);
                mRlTodayFinsh.setVisibility(View.VISIBLE);
                mTvMore5.setVisibility(View.GONE);
                mIvline.setVisibility(View.GONE);
            } else if (wordPlanViewType == WordPlanViewType.VIEW_TTPE_TODAY_FINISH) {
                mCardView1.setVisibility(View.VISIBLE);
                mCardView2.setVisibility(View.GONE);
                mRlTodayLearning.setVisibility(View.GONE);
                mRlTodayFinsh.setVisibility(View.VISIBLE);
                mTvMore5.setVisibility(View.VISIBLE);
                mIvline.setVisibility(View.VISIBLE);
                setTodayFinshText(planAndWorListBean);
            } else if (wordPlanViewType == WordPlanViewType.VIEW_TTPE_LEARNNING) {
                mCardView1.setVisibility(View.VISIBLE);
                mCardView2.setVisibility(View.GONE);
                mRlTodayLearning.setVisibility(View.VISIBLE);
                mRlTodayFinsh.setVisibility(View.GONE);
                setTodayLearningText(planAndWorListBean);
            }
        }
        hideCricleProgress();
    }

    private void setTodayFinshText(PlanAndWorListBean planAndWorListBean) {
        if (planAndWorListBean == null) {
            return;
        }

        mTvBookName.setText(planAndWorListBean.getPlanName());
        mRestDayCount.setCount(planAndWorListBean.getLastday());
        mOneDayNumber.setCount(getDayCount(planAndWorListBean));
        mTvMore5.setText("再来" + getDayCount(planAndWorListBean) + "个");

        int wordsum = planAndWorListBean.getWordsum();
        mTvWordAll.setText("/" + wordsum + "");
        mTvLearnedOfAll.setText(planAndWorListBean.getCompletecount() + "");
        if (wordsum > 0) {
            mProgressBar.setMax(wordsum);
            mProgressBar.setProgress(planAndWorListBean.getCompletecount());
        }


    }

    private void setTodayLearningText(PlanAndWorListBean planAndWorListBean) {
        if (planAndWorListBean == null) {
            return;
        }


        mTvBookName.setText(planAndWorListBean.getPlanName());
        mRestDayCount.setCount(planAndWorListBean.getLastday());
        mOneDayNumber.setCount(getDayCount(planAndWorListBean));

        int wordsum = planAndWorListBean.getWordsum();
        mTvWordAll.setText("/" + wordsum + "");
        mTvLearnedOfAll.setText(planAndWorListBean.getCompletecount() + "");
        if (wordsum > 0) {
            mProgressBar.setMax(wordsum);
            mProgressBar.setProgress(planAndWorListBean.getCompletecount());
        }
        List<TodayAndReviewWordBean> todayList = planAndWorListBean.getToday();
        List<TodayAndReviewWordBean> reviewList = planAndWorListBean.getReview();
        String todayText;
        if (todayList == null || todayList.size() == 0) {
            todayText = "今日需新学0";
        } else {
            int needLearnCount = todayList.size() - TODAY_NEW_WORD_INDEX >= 0 ? todayList.size() - TODAY_NEW_WORD_INDEX : 0;
            todayText = String.format(getResources().getString(R.string.today_learn), needLearnCount + "", todayList.size() + "");
        }
        mTvTodayLearn.setText(todayText);
        String reviewText;
        if (REVIEW_WORDS_TO_REVIEW != -1) {
            reviewText = String.format(getResources().getString(R.string.today_revise), REVIEW_WORDS_TO_REVIEW + "");
        } else {
            if (reviewList == null || reviewList.size() == 0) {
                reviewText = String.format(getResources().getString(R.string.today_revise), "0");
            } else {
                reviewText = String.format(getResources().getString(R.string.today_revise), reviewList.size() + "");
            }
        }

        mTvTodayRevise.setText(reviewText);
    }

    public int getDayCount(PlanAndWorListBean planAndWorListBean) {
        if (planAndWorListBean == null) {
            return 0;
        } else {
            List<TodayAndReviewWordBean> todayList = planAndWorListBean.getToday();
            if (todayList != null && todayList.size() > 0) {
                return todayList.size();
            } else {
                return planAndWorListBean.getDayCount();
            }
        }

    }

    @Override
    public void onClick(View v) {
        if (!DoubleClickCheckUtils.vertify500Duration()) {
            return;
        }
        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
            return;
        }
        int id = v.getId();
        if (id == R.id.tv_change_plan) {
            if (mPlanAndWorListBean != null) {
                String planName = mPlanAndWorListBean.getPlanName();
                int wordsum = mPlanAndWorListBean.getWordsum();
                int completecount = mPlanAndWorListBean.getCompletecount();
                int dayCount = mPlanAndWorListBean.getDayCount();
                int bookId = mPlanAndWorListBean.getBookId();
                WordJumpManager.jumpToChangeWordPlanActivity(R.string.go_back, planName, bookId, wordsum, completecount, dayCount, WordPlanActivity.this);
            }

        } else if (id == R.id.tv_learn_other_word) {
            if (mPlanAndWorListBean != null) {
                int bookId = mPlanAndWorListBean.getBookId();
                WordJumpManager.jumpToSelectVacabularyActivity(R.string.go_back, WordPlanActivity.this, bookId, IntentValue.JumpSelectVocabularyType.FROM_CHANGE_PLAN);
            }

        } else if (id == R.id.btn_retry || id == R.id.btn_failed_retry) {
            getDataFromNet();
        } else if (id == R.id.btn_recite_word) {
            startBeiWord();
//            showGetSDcardPermissDialog();
        } else if (id == R.id.btn_word_daka) {
            WordJumpManager.jumpToDaKaActivity(R.string.go_back, WordPlanActivity.this, null);
        } else if (id == R.id.btn_word_pk_2 || id == R.id.btn_word_pk_1) {
            WordJumpManager.jumpToWordPKActivity(R.string.go_back, WordPlanActivity.this);
        } else if (id == R.id.tv_word_list) {
            jumpToReciteWordList(mPlanAndWorListBean, new CallBackWordBookExist() {
                @Override
                void wordBookExist() {
                    WordJumpManager.jumpToReciteWordLisActivity(R.string.go_back, WordPlanActivity.this);
                }
            });
        } else if (id == R.id.tv_more5) {
            if (mPlanAndWorListBean == null) {
                return;
            }
            reciteWordStart(mPlanAndWorListBean, new CallBackWordBookExist() {
                @Override
                void wordBookExist() {
                    //再来5个时，上次完成时间置为0，下次进来时，应该是学习中状态
                    CWSys.setSharedLong(ListenSpeakUtil.getCompleteTimeKey(), 0);
                    buttonReciteWord();
                }
            });
        } else if (id == R.id.tv_learn_again) {
            if (mPlanAndWorListBean == null) {
                return;
            }
            //再来一遍时，上次完成时间置为0，下次进来时，应该是学习中状态
            CWSys.setSharedLong(ListenSpeakUtil.getCompleteTimeKey(), 0);
            final int userId = (int) EApplication.getInstance().getUserInfoBase().getUserId();
            showCricleProgress();
            WordDao.getInstance().getAgain(userId, mPlanAndWorListBean.getBookId(), new BaseExtCallBack(WordPlanActivity.this) {
                @Override
                public void failed(Object data) {
                    super.failed(data);
                    hideCricleProgress();
                    if (!NetworkUtils.isOnline()) {
                        ToastUtil.INSTANCE.toastCenterNoNetError();
                    } else if (data instanceof TimeoutError) {
                        ToastUtil.INSTANCE.toastCenterError("连接超时，请稍后重试");
                    }
                }

                @Override
                public void failed(int errorCode, Object data) {
                    super.failed(errorCode, data);
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterErrorWithErrorCode(R.string.server_error, errorCode);
                }

                @Override
                public void success(Object data) {
                    loadData();
                }
            });
        }
    }

    private void jumpToReciteWordList(PlanAndWorListBean mPlanAndWorListBean, CallBackWordBookExist callBackWordBookExist) {
        flag = JUMP_TO_RECITE_WORD_LIST;
        downLoadFileCheck(mPlanAndWorListBean, callBackWordBookExist);
    }

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;

    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetSDcardPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写本地存储权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                startBeiWord();
                            }
                        }
                    });
        } else {
            startBeiWord();
        }
        return true;
    }

    private void startBeiWord() {
        reciteWordStart(mPlanAndWorListBean, new CallBackWordBookExist() {
            @Override
            void wordBookExist() {
                buttonReciteWord();
            }
        });
    }


    private void buttonReciteWord() {

        if (mPlanAndWorListBean != null) {
            CopyOnWriteArrayList<WordDetail> todayWords = new CopyOnWriteArrayList<>();
            List<TodayAndReviewWordBean> todayList = mPlanAndWorListBean.getToday();
            if (todayList != null) {
                for (TodayAndReviewWordBean todayWordBean : todayList) {
                    WordDetail wordDetail = new WordDetail();
                    wordDetail.setdId(todayWordBean.getInterpretationId() + "");
                    todayWords.add(wordDetail);
                }
            }
            CopyOnWriteArrayList<WordDetail> reviewWords = new CopyOnWriteArrayList<>();
            List<TodayAndReviewWordBean> reviewList = mPlanAndWorListBean.getReview();
            if (reviewList != null) {
                for (TodayAndReviewWordBean reviewWordBean : reviewList) {
                    WordDetail wordDetail = new WordDetail();
                    wordDetail.setdId(reviewWordBean.getInterpretationId() + "");
                    reviewWords.add(wordDetail);
                }
            }
            WordJumpManager.jumpToWordStudyActivity(R.string.go_back, todayWords, reviewWords, WordPlanActivity.this, RequestCode.WordPlanResquestCode.REQ_CODE_TO_RECITE_WORD);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        loadData();
        Log.e(TAG, "onNewIntent: ");
    }

    private void reciteWordStart(PlanAndWorListBean mPlanAndWorListBean, CallBackWordBookExist callBackWordBookExist) {
        flag = JUMP_TO_RECITE_WORD_START_OR_MORE;
        downLoadFileCheck(mPlanAndWorListBean, callBackWordBookExist);
    }


    private void downLoadFileCheck(PlanAndWorListBean mPlanAndWorListBean, final CallBackWordBookExist callBackWordBookExist) {
//        String url = "https://file.dzb.ciwong.com/epaper/20181030110510/BookWordList_2346.zip";
        if (mPlanAndWorListBean != null)
            WordBookDownloadManager.downLoadFile(WordPlanActivity.this, mPlanAndWorListBean.getBookId() + "", mPlanAndWorListBean.getPackageUrl(), new DownloadCallBack() {
                @Override
                protected void downloadAlready() {
                    // TODO: 2018/9/26 next
                    if (callBackWordBookExist != null)
                        callBackWordBookExist.wordBookExist();
                }

                @Override
                protected void downloadStart() {
                    showDownloadProgress("玩命加载中,请耐心等待......");
                    showCancelButtonOfDownloadProgress();
                }

                @Override
                protected void downloadFail(Object data) {
                    hideDownloadHorizontalProgressBar();
                    hideCancelButtonOfDownloadProgress();
                    hideDownloadProgress();
                }

                @Override
                protected void downloadException(Object data) {
                    hideDownloadHorizontalProgressBar();
                    hideCancelButtonOfDownloadProgress();
                    hideDownloadProgress();
                }
            });
    }


    public void onEventMainThread(EventBusFactory.DownloadEvent item) {
        try {
            downLoadInfo = item.getInfo();
            Log.e(TAG, "onEventMainThread : " + downLoadInfo.getBookId() + "  " + downLoadInfo.getSavePath() +
                    "  " + downLoadInfo.getStatus() + "  " + downLoadInfo.getUrl() + "  progress:" + downLoadInfo.getProgress());
            if (downLoadInfo != null) {
                if (downLoadInfo.getStatus() == DownloadStatus.STATUS_FILE_DOWNLOAD) {
                    hideDownloadHorizontalProgressBar();
                    hideCancelButtonOfDownloadProgress();
                } else if (downLoadInfo.getStatus() == DownloadStatus.STATUS_COMPLETED) {
                    String upZipFilePath = WordBookDownloadManager.getUpZipFilePath(downLoadInfo.getSavePath());
                    String filePath = upZipFilePath + File.separator + "resource.json";
                    WordBookDownloadManager.getWordBookList(this, filePath, new DeserializeCallBack() {
                        @Override
                        protected void deserializesuccess(Object data) {
                        }

                        @Override
                        public void deserializeFail(Object data) {
                            hideDownloadProgress();
                        }

                        @Override
                        protected void insertDBsuccess(Object data) {
                            CWLog.d(TAG, "insertDBsuccess:" + "插入数据库数据成功");
                            hideDownloadProgress();
                            deleteReciteWordBookFile(downLoadInfo.getSavePath());
                            final String bookId = downLoadInfo.getBookId();//注意此处 bookId为原始bookId+bookId(Sting类型)
                            int hashCodeUrl = downLoadInfo.getUrl().hashCode();
                            DBWordBookStateManagerAsyn.getInstance().addOrUpdateAsyn(bookId, hashCodeUrl, new DBCallBack() {
                                @Override
                                public void dbResult(Object data) {
                                    boolean flag = (Boolean) data;
                                    if (flag) {
                                        takeNextStep();
                                    }
                                }
                            });
                        }

                        @Override
                        protected void insertDBFail(Object data) {
                            hideDownloadProgress();
                            ToastUtil.INSTANCE.toastCenterError("数据库插入错误");
                            deleteReciteWordBookFile(downLoadInfo.getSavePath());
                        }
                    });
                } else if (downLoadInfo.getStatus() == DownloadStatus.STATUS_FAILED) {
                    ToastUtil.INSTANCE.toastCenterError(R.string.download_fail);
                    hideDownloadProgress();
                } else if (downLoadInfo.getStatus() == DownloadStatus.STATUS_FAILED_SDISFULL) {
                    ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_sdfull_and_retry);
                    hideDownloadProgress();
                } else if (downLoadInfo.getStatus() == DownloadStatus.STATUS_FAILED_UNZIP) {
                    ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_unzip_and_retry);
                    hideDownloadProgress();
                } else if (downLoadInfo.getStatus() == DownloadStatus.STATUS_DOWNLOADING) {

                    updateDownloadProgress(downLoadInfo.getProgress());
                }
            } else {
                hideDownloadProgress();
                CWLog.e(TAG, "downLoadInfo == null:");
            }
        } catch (Exception e) {
            e.getStackTrace();
            hideDownloadProgress();
        }
    }

    private void deleteReciteWordBookFile(String savePath) {
        //插入数据库成功或者失败 都要删除文件，下次会重新下载
        WordBookDownloadManager.deleteReciteWordBookFile(savePath);
    }


    private void takeNextStep() {
        if (flag == JUMP_TO_RECITE_WORD_LIST) {
            WordJumpManager.jumpToReciteWordLisActivity(R.string.go_back, WordPlanActivity.this);
        } else if (flag == JUMP_TO_RECITE_WORD_START_OR_MORE) {
            buttonReciteWord();
        }
    }

    private abstract class CallBackWordBookExist {
        abstract void wordBookExist();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCode.WordPlanResquestCode.REQ_CODE_TO_RECITE_WORD:
                    loadData();
                    break;
                case CODE_REQUEST_WRITESD_PERMISSION:
                    startBeiWord();
                    break;
            }
        }
    }

}
